use chrono::{offset::LocalResult, DateTime, FixedOffset, Local, NaiveDate, NaiveTime, TimeZone};

pub fn get_sec_timestamp_by_str(time_str: &str) -> i64 {
    if let Ok(date) = NaiveDate::parse_from_str(time_str, "%Y-%m-%d") {
        if let Some(option) = date.and_hms_opt(0, 0, 0) {
            if let Some(opt1) = FixedOffset::east_opt(8 * 60 * 60) {
                if let LocalResult::Single(i2) = option.and_local_timezone(opt1) {
                    return i2.timestamp();
                }
            }
        }
    }

    return 0; // TODO: temp fix bug just
}

pub fn get_today_timestamp() -> i64 {
    let time = Local::now();
    if let Some(noon) = NaiveTime::from_hms_opt(0, 0, 0) {
        if let LocalResult::Single(v) = time.with_time(noon) {
            return v.timestamp();
        }
    }

    return 0;
}

pub fn get_date_from_timestamp(ts: i64) -> String {
    let time = DateTime::from_timestamp(ts, 0)
        .expect(format!("timestamp transport error: {}", ts).as_str());
    // convert timestamp `ts` to NaiveDateTime
    use chrono_tz::Asia::Shanghai;

    let time1 = time.naive_local();
    let datetime_shanghai = Shanghai.from_utc_datetime(&time1);
    // formated print datetime
    let formatted_datetime = datetime_shanghai.format("%Y-%m-%d").to_string();

    formatted_datetime
}

// TODO: mod test
